package com.harisucici.websocketlib.room;


import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Transaction;
import androidx.room.Update;

import com.harisucici.websocketlib.entities.receive.CurrentSessionReceive;

import java.util.List;

@Dao
public abstract class CurrentDao {
    @Insert
    public abstract void insertMsg(CurrentSessionReceive entity);



    @Update
    public abstract void updateMsg(CurrentSessionReceive entity);

    @Query("delete from CurrentSessionReceive")
    public abstract void deleteAll();

    @Query("delete from CurrentSessionReceive where timelineId=:timelineId")
    public abstract void deleteTimeline(String timelineId);

    @Query("select * from CurrentSessionReceive")
    public abstract List<CurrentSessionReceive> listMsg();

    @Query("select * from CurrentSessionReceive where appSeqId=:appSeqId")
    public abstract CurrentSessionReceive findMsgByAppSeqId(long appSeqId);

    @Query("select * from CurrentSessionReceive where sequenceId=:sequenceId")
    public abstract CurrentSessionReceive findMsgBySeqId(long sequenceId);

    @Query("select * from CurrentSessionReceive where timestamp=:timestamp")
    public abstract CurrentSessionReceive findMsgByTime(long timestamp);

    @Query("select * from CurrentSessionReceive where timelineId=:timelineId order by timestamp asc")
    public abstract LiveData<List<CurrentSessionReceive>> findCurrentTimelineUp(String timelineId);


    @Query("select * from CurrentSessionReceive where timelineId=:timelineId order by timestamp desc")
    public abstract LiveData<List<CurrentSessionReceive>> findCurrentTimelineDown(String timelineId);

    @Query("select * FROM CurrentSessionReceive ORDER BY id DESC LIMIT 0,1")
    public abstract CurrentSessionReceive findTop();


//    @Query("update  where appSeqId=:appSeqId")
//    public abstract void updateMsgById(CurrentSessionReceive entity,long appSeqId);


    @Transaction
    public void updateStateById(CurrentSessionReceive entity) {
        CurrentSessionReceive temp = findMsgByAppSeqId(entity.getAppSeqId());
        // 不存在这条消息(新消息)
        if (entity.getAppSeqId() == 0 || temp == null) {
            insertMsg(entity);
        } else {
//            temp.setSendState(0);
            entity.setSendState(0);
            entity.setId(temp.getId());
            updateMsg(entity);
        }
    }
}
